package com.zuikaku.controller;

import com.zuikaku.pojo.Item;
import com.zuikaku.pojo.Order;
import com.zuikaku.pojo.TempUser;
import com.zuikaku.pojo.User;
import com.zuikaku.service.ItemService;
import com.zuikaku.service.OrderService;
import com.zuikaku.service.UserService;
import com.zuikaku.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@RequestMapping("/user")
@SessionAttributes("activeUser")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private OrderService orderService;

    @PostMapping("/login")
    public String login(@RequestParam("username")String userName,@RequestParam("password")String password, Model model){

        User user = userService.getUserByUsernameAndPassword(userName,password);
        if(user !=null){
            model.addAttribute("activeUser",user);
            return "redirect:/order/getOrdersByItemIdAndUserId/"+user.getUserId()+"/0";
        }else {
            model.addAttribute("msg","登陆失败");
            return "error";
        }

    }


    @ResponseBody
    @GetMapping("/getCurrentUserVO")
    public String getCurrentUserVO(@SessionAttribute("activeUser")User activeUser){
        int userId = activeUser.getUserId();
        UserVO userVO = userService.getUserVOByPk(userId);
        return userVO.toString();
    }


    @ResponseBody
    @GetMapping("/createOrder")
    public String createOrder(@SessionAttribute("activeUser")User activeUser,@RequestParam("itemId")Integer itemId){
        return orderService.createOrder(activeUser,itemId);
    }

}
